import 'dart:convert';

import 'package:kkhousekeep/models/home_banner_entity.dart';
import 'package:kkhousekeep/models/home_community_detail_entity.dart';
import 'package:kkhousekeep/models/home_community_entity.dart';
import 'package:kkhousekeep/models/home_village_change_entity.dart';
import 'package:kkhousekeep/models/home_village_entity.dart';
import 'package:kkhousekeep/net/base_connect.dart';
import 'package:kkhousekeep/net/respnse_code.dart';
import 'package:kkhousekeep/tools/dialog_util.dart';
import 'package:kkhousekeep/tools/toast_util.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../models/home_check_home_bind_entity.dart';
import '../models/home_exist_new_mag_entity.dart';
import '../models/home_notice_entity.dart';
import '../models/home_room_entity.dart';
import '../models/room_token_entity.dart';
import '../page/login/login_controller.dart';
import '../tools/shared_preferences.dart';
import 'api.dart';

class HomeConnect extends BaseConnect {
  Future<HomeRoomObjList> getRoomInfo() async {
    var defaultRoom = HomeRoomObjList().copyWith(
        roomId: -1,
        cityName: '',
        communityName: '',
        buildingName: '',
        unitName: '',
        roomName: '');
    var sp = await SharedPreferences.getInstance();
    if (sp.containsKey(SpKey.roomInfo)) {
      HomeRoomObjList roomObjList = HomeRoomObjList.fromJson(
          jsonDecode(sp.getString(SpKey.roomInfo) ?? ''));
      return Future.value(roomObjList);
    }
    List<HomeRoomObjList> rooms = await getRooms();
    if (rooms.isNotEmpty) {
      var room = rooms[0];
      sp.setString(SpKey.roomInfo, jsonEncode(room.toJson()));
      return Future.value(room);
    }
    return Future.value(defaultRoom);
  }

  Future<HomeVillageObj> getPropertyVillagesInfo() async {
    var defaultVillage = HomeVillageObj().copyWith(id: -1, name: '');
    var sp = await SharedPreferences.getInstance();
    if (sp.containsKey(SpKey.villageInfo)) {
      HomeVillageObj village = HomeVillageObj.fromJson(
          jsonDecode(sp.getString(SpKey.villageInfo) ?? ''));
      return Future.value(village);
    }
    List<HomeVillageObj> villages = await getPropertyVillages();
    //物业端返回的token与列表的第一个数据不对应，需要进行匹配，若匹配不上则使用第一个小区
    if (villages.isNotEmpty) {
      var currentVillageId = await getSp().getCid();
      var village = villages.firstWhere(
          (element) => element.id == currentVillageId,
          orElse: () => defaultVillage..id = -2);
      if (village.id == -2) {
        sp.setString(SpKey.villageInfo, jsonEncode(villages[0].toJson()));
      } else {
        sp.setString(SpKey.villageInfo, jsonEncode(village.toJson()));
      }
      return Future.value(village);
    }
    return Future.value(defaultVillage);
  }

  Future<List<HomeVillageObj>> getPropertyVillages() async {
    var response = await get(Api.getPropertyVillages);
    if (response.body == null) {
      DialogUtil.showNetworkError();
      return Future.value([]);
    }
    HomeVillageEntity entity = HomeVillageEntity.fromJson(response.body);
    if (ResponseCode.success == entity.code) {
      return Future.value(entity.obj);
    }
    return Future.value([]);
  }

  Future<List<HomeRoomObjList>> getRooms() async {
    var response = await post(Api.getRoomList, {});
    if (response.body == null) {
      DialogUtil.showNetworkError();
      return Future.value([]);
    }
    HomeRoomEntity entity = HomeRoomEntity.fromJson(response.body);
    if (ResponseCode.success == entity.code) {
      return Future.value(entity.obj.list);
    }
    return Future.value([]);
  }

  Future<List<HomeBannerObjList>> getBannerList() async {
    var response = await post(Api.getBannerList, {});
    if (response.body == null) {
      DialogUtil.showNetworkError();
      return Future.value([]);
    }
    HomeBannerEntity entity = HomeBannerEntity.fromJson(response.body);
    if (ResponseCode.success == entity.code) {
      return Future.value(entity.obj.list);
    }
    return Future.value([]);
  }

  Future<List<HomeNoticeObjList>> getNoticeList({
    required UserType userType,
  }) async {
    String url = userType == UserType.property
        ? Api.getPropertyNoticeList
        : Api.getNoticeList;
    var response = await post(url, {});
    if (response.body == null) {
      DialogUtil.showNetworkError();
      return Future.value([]);
    }
    HomeNoticeEntity entity = HomeNoticeEntity.fromJson(response.body);
    if (ResponseCode.success == entity.code && entity.obj.list.isNotEmpty) {
      return Future.value(entity.obj.list);
    }
    return Future.value([]);
  }

  Future<List<HomeCommunityObjList>> getCommunityList(
    int serviceType,
  ) async {
    var response = await post(Api.getServiceList, {
      'serviceType': serviceType,
    });
    if (response.body == null) {
      DialogUtil.showNetworkError();
      return Future.value([]);
    }
    HomeCommunityEntity entity = HomeCommunityEntity.fromJson(response.body);
    if (ResponseCode.success == entity.code) {
      return Future.value(entity.obj.list);
    }
    return Future.value([]);
  }

  Future<HomeCommunityDetailObj> getCommunityDetail({
    required int id,
    required int serviceType,
  }) async {
    var response = await post(Api.getServiceInfo, {
      'id': id,
      'serviceType': serviceType,
    });
    if (response.body == null) {
      DialogUtil.showNetworkError();
      return Future.value(
        HomeCommunityDetailObj().copyWith(
          id: -1,
          title: '',
          contacts: '',
          contactWay: '',
          showImages: [],
          describe: '',
          publishTime: '',
        ),
      );
    }
    HomeCommunityDetailEntity entity =
        HomeCommunityDetailEntity.fromJson(response.body);
    if (ResponseCode.success == entity.code) {
      return Future.value(entity.obj);
    }
    return Future.value(
      HomeCommunityDetailObj().copyWith(
        id: -1,
        title: '',
        contacts: '',
        contactWay: '',
        showImages: [],
        describe: '',
        publishTime: '',
      ),
    );
  }

  Future<HomeExistNewMagObj> getServiceNewMsg() async {
    UserType userType = await getSp().getUserType();
    String url = userType == UserType.property
        ? Api.getPropertyExistNewMsg
        : Api.getExistNewMsg;

    var response = await get(url);
    if (response.body == null) {
      DialogUtil.showNetworkError();
      return Future.value(HomeExistNewMagObj().copyWith(
        noticeExist: false,
        workOrderExist: false,
        billExist: false,
      ));
    }
    HomeExistNewMagEntity entity =
        HomeExistNewMagEntity.fromJson(response.body);
    if (ResponseCode.success == entity.code) {
      if (userType == UserType.property) {
        entity.obj.billExist = false;
        return Future.value(entity.obj);
      }
      entity.obj.workOrderExist = false;
      return Future.value(entity.obj);
    }

    return Future.value(HomeExistNewMagObj().copyWith(
      noticeExist: false,
      workOrderExist: false,
      billExist: false,
    ));
  }

  Future<HomeCheckHomeBindEntity?> checkHomeBind() async {
    var response = await get(Api.checkRoomBind);
    if (response.body == null) {
      DialogUtil.showNetworkError();
      return Future.value();
    }
    return Future.value(HomeCheckHomeBindEntity.fromJson(response.body));
  }

  Future<String> switchHouse({
    required int id,
  }) async {
    var response = await post(Api.changeHouse, {'roomID': id});
    if (response.body == null) {
      DialogUtil.showNetworkError();
      return Future.value('');
    }
    RoomTokenEntity entity = RoomTokenEntity.fromJson(response.body);
    if (ResponseCode.success == entity.code) {
      return Future.value(entity.obj.token);
    }

    ToastUtils.showToast(tip: '切换失败');
    return Future.value('');
  }

  Future<String> switchPropertyVillage({
    required int id,
  }) async {
    var response = await post(Api.changePropertyVillage, {'cid': id});
    if (response.body == null) {
      DialogUtil.showNetworkError();
      return Future.value('');
    }
    HomeVillageChangeEntity entity =
        HomeVillageChangeEntity.fromJson(response.body);
    if (ResponseCode.success == entity.code) {
      return Future.value(entity.obj.token);
    }
    ToastUtils.showToast(tip: '切换失败');
    return Future.value('');
  }
}
